Page({
  data: {
    isLoggedIn: false,
    userInfo: null,
    orderStats: {
      pending: 0,
      paid: 0,
      completed: 0
    }
  },
  onLoad() {
    this.checkLoginStatus();
  },
  onShow() {
    this.checkLoginStatus();
    if (this.data.isLoggedIn) {
      this.getOrderStats();
    }
  },
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      isLoggedIn: !!userInfo,
      userInfo: userInfo
    });
  },
  getOrderStats() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) return;
    
    wx.request({
      url: 'http://localhost:3000/api/order',
      method: 'GET',
      data: { user_id: userInfo.id },
      success: (res) => {
        if (res.data && res.data.code === 0) {
          const orders = res.data.data;
          const stats = {
            pending: orders.filter(o => o.status === '待支付').length,
            paid: orders.filter(o => o.status === '已支付').length,
            completed: orders.filter(o => o.status === '已完成').length
          };
          this.setData({ orderStats: stats });
        }
      }
    });
  },
  goToLogin() {
    wx.navigateTo({
      url: '/pages/user/login/index'
    });
  },
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('userInfo');
          this.setData({
            isLoggedIn: false,
            userInfo: null,
            orderStats: { pending: 0, paid: 0, completed: 0 }
          });
          wx.showToast({ title: '已退出登录', icon: 'success' });
        }
      }
    });
  },
  goToOrders(e) {
    if (!this.data.isLoggedIn) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    const status = e.currentTarget.dataset.status;
    wx.navigateTo({
      url: `/pages/user/order/index?status=${status}`
    });
  },
  goToAdmin() {
    wx.navigateTo({
      url: '/pages/admin/login/index'
    });
  },
  goToAI() {
    wx.navigateTo({
      url: '/pages/user/ai/index'
    });
  }
}); 